const { User, Resource } = require('../models');
const cozeClient = require('../utils/cozeClient');
const eduSystemClient = require('../utils/eduSystemClient');

/**
 * 生成教学设计
 * @route POST /api/design/generate
 */
const generateDesign = async (req, res, next) => {
  try {
    const { teachingGoal, duration, style, userId = 1 } = req.body;
    
    // 1. 获取用户信息和风格偏好
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 获取课程大纲和知识点树（模拟从教务系统获取）
    // 实际项目中应该根据请求参数获取特定课程的大纲
    const courseId = req.body.courseId || 1; // 默认使用ID为1的课程
    const courseOutline = await eduSystemClient.getCourseOutline(courseId);
    
    // 3. 获取学生学情数据（模拟从教务系统获取）
    const learningStatus = await eduSystemClient.getStudentLearningStatus(courseId);
    
    // 4. 融合数据，构建Coze智能体输入参数
    const cozeParams = {
      teachingGoal,
      duration: `${duration}分钟`,
      style: style || user.stylePreference?.teachingStyle || '标准教学风格',
      courseOutline: {
        courseName: courseOutline.courseName,
        teachingEmphasis: courseOutline.teachingEmphasis.map(item => item.name).join('、')
      },
      studentLearningStatus: {
        weakPoints: learningStatus.weakKnowledgePoints.map(item => item.name).join('、'),
        learningStyles: Object.entries(learningStatus.learningStyles)
          .sort((a, b) => b[1] - a[1])
          .map(([style, ratio]) => `${style}(${(ratio * 100).toFixed(0)}%)`)
          .join('、')
      },
      outputFormat: 'JSON' // 请求结构化输出
    };
    
    // 5. 调用Coze智能体生成教学设计
    const designResult = await cozeClient.callBot('designBot', cozeParams);
    
    // 6. 处理智能体返回结果，套入学校教案模板
    // 这里简化处理，实际项目中可能需要更复杂的模板处理
    const designContent = {
      title: designResult.title || `${courseOutline.courseName}教学设计`,
      objectives: designResult.objectives || [],
      keyPoints: designResult.keyPoints || [],
      difficultyPoints: designResult.difficultyPoints || [],
      methods: designResult.methods || [],
      process: designResult.process || [],
      evaluation: designResult.evaluation || '',
      duration: duration,
      style: style || user.stylePreference?.teachingStyle || '标准教学风格',
      generatedAt: new Date().toISOString(),
      courseInfo: {
        name: courseOutline.courseName,
        totalHours: courseOutline.totalHours,
        credit: courseOutline.credit
      }
    };
    
    // 7. 保存到资源表
    const resource = await Resource.create({
      userId,
      type: 'design',
      content: designContent,
      isSaved: false
    });
    
    // 8. 更新用户风格偏好
    if (style && (!user.stylePreference || user.stylePreference.teachingStyle !== style)) {
      const stylePreference = user.stylePreference || {};
      stylePreference.teachingStyle = style;
      await user.update({ stylePreference });
    }
    
    // 9. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        designContent,
        resourceId: resource.id
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 导出教学设计为PDF
 * @route GET /api/design/export/:resourceId
 */
const exportDesign = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 1. 查询资源
    const resource = await Resource.findOne({
      where: {
        id: resourceId,
        type: 'design'
      }
    });
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '教学设计资源不存在'
      });
    }
    
    // 2. 生成PDF（实际项目中应该调用PDF生成库）
    // 这里模拟PDF生成，返回成功消息
    
    // 模拟PDF生成延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 3. 返回结果
    res.json({
      code: 200,
      success: true,
      message: 'PDF导出功能在实际项目中实现',
      data: {
        resourceId,
        fileName: `教学设计_${resourceId}.pdf`,
        // 实际项目中应该返回PDF文件下载链接
        downloadUrl: `/downloads/designs/${resourceId}.pdf`
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取教学设计详情
 * @route GET /api/design/:resourceId
 */
const getDesignDetail = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 查询资源
    const resource = await Resource.findOne({
      where: {
        id: resourceId,
        type: 'design'
      }
    });
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '教学设计资源不存在'
      });
    }
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        resourceId: resource.id,
        userId: resource.userId,
        designContent: resource.content,
        generateTime: resource.generateTime,
        isSaved: resource.isSaved
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  generateDesign,
  exportDesign,
  getDesignDetail
};